package com.chatplus.application.controller.api.extend;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chatplus.application.common.constant.RedisPrefix;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.ImgResultDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

/**
 * 获取每日壁纸
 */
@Validated
@RestController
@RequestMapping("/api/extend/")
@Tag(name = "微博第三方API", description = "微博第三方API")
public class WallpaperExtendController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(WallpaperExtendController.class);

    private final RedissonClient redissonClient;

    public WallpaperExtendController(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @GetMapping("/todayWallpaper")
    @Operation(summary = "获取今日壁纸")
    @SaIgnore
    public ImgResultDto todayWallpaper() {
        String startDate = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        String redisKey = RedisPrefix.EXTEND_REDIS_PREFIX_TEST + "todayWallpaper:"+startDate;
        RBucket<ImgResultDto> rBucket = redissonClient.getBucket(redisKey, new SerializationCodec());
        ImgResultDto cache = rBucket.isExists() ? rBucket.get() : null;
        if (cache!=null) {
            return cache;
        }
        LOGGER.message("获取今日壁纸").info();
        String url = "https://raw.onmicrosoft.cn/Bing-Wallpaper-Action/main/data/zh-CN_all.json";
        try (HttpResponse response = HttpUtil.createGet(url).execute()){
            String dataText = response.body();
            JSONObject responseMap = JSONUtil.parseObj(dataText);
            JSONArray dataArray = responseMap.getJSONArray("data");
            if (dataArray.isEmpty()){
                throw new BadRequestException("获取今日壁纸失败");
            }
            JSONObject data = dataArray.getJSONObject(0);
            cache = new ImgResultDto();
            cache.setUrl(URLEncoder.encode("https://www.bing.com" + data.getStr("url"), StandardCharsets.UTF_8));
            cache.setRevisedPrompt(data.getStr("title"));

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime endOfDay = LocalDateTime.of(now.toLocalDate(), LocalTime.MAX);
            Duration duration = Duration.between(now, endOfDay);
            long minutesRemaining = duration.toMinutes();

            rBucket.set(cache, Duration.ofMinutes(minutesRemaining));
        } catch (Exception e) {
            LOGGER.message("获取今日壁纸失败").exception(e).error();
        }
        return cache;
    }
}
